<?php

namespace system\model;

use houdunwang\model\Model;
use houdunwang\validate\Validate;

class Admin extends model
{
	//操作的数据表
	protected $table = "admin";

	//登录
	public function login()
	{
		//1.验证数据不能为空
		$data = [
			'admin_username'=>q('post.admin_username'),
			'admin_password'=>q('post.admin_password'),
			'code'=>q('post.code'),
		];
		$res = Validate::make( [
			[ 'admin_username', 'isnull', '请输入用户名', 3 ],
			[ 'admin_password', 'isnull', '请输入密码', 3 ],
			[ 'code', 'isnull', '请输入验证码', 3 ],
		] ,$data);
		//2.比对用户名密码是否正确
//		var_dump(Crypt::encrypt($_POST['admin_password']));
//		die();



			$userInfo = $this->where('admin_username',$data['admin_username'])->first();
			if(!$userInfo){
				return ['valid'=>0,'msg'=>'用户名不正确'];
			}
			//校验密码
		//WwyrpXyXKdvyevMCYOpH7g==
		//file_put_contents('./99.php',password_hash($data['admin_password'],PASSWORD_DEFAULT));

			if(!password_verify($data['admin_password'],$userInfo['admin_password']))
			{

				return ['valid'=>0,'msg'=>'用户密码不正确'];
			}

		//3.比对验证码是否正确
			if(!Code::auth( 'code' ))
			{
				return ['valid'=>0,'msg'=>'验证码不正确'];
			}
		//4.将当前登录用户信息存入session
		Session::set('admin.admin_id',$userInfo['admin_id']);
		Session::set('admin.admin_username',$userInfo['admin_username']);
		//5.返回成功
		return ['valid'=>1,'msg'=>'登录成功'];
	}

	//修改密码
	public function changePassword($data)
	{
//		dd($data);
		Validate::make([
			['admin_password','required','请输入原始密码',Validate::MUST_VALIDATE],
			['new_password','required','请输入新密码',Validate::MUST_VALIDATE],
			['retry_password','confirm:new_password','确认密码跟新密码不一致',Validate::MUST_VALIDATE],
		]);
		//比对原始密码是否正确
		$userInfo = self::find(Session::get('admin.admin_id'));
		if(!password_verify($data['admin_password'],$userInfo['admin_password'])){
			return ['valid'=>0,'message'=>'原始密码不正确'];
		}
		//走到这里说明原始密码是正确的，并且新密码和确认密码也没有问题
		$userInfo->admin_password = password_hash($data['new_password'],PASSWORD_DEFAULT);
		$userInfo->save();
		return ['valid'=>1,'message'=>'修改成功'];
	}
}